<template>
<div>
  <el-card class="search-card">
    <BasicForm
      ref="formData"
      :isScalingBtn="true"
      :formColumns="formItemList"
      :dataSource="formData"
      :defaultExpandStatus="false"
      :handleSearchForm="handleQueryForm"
      :colNumOfRow="4"
      @getFormData="getFormData"
    ></BasicForm>
  </el-card>
  <el-card class="table-card">
    <basic-table
      showActionCol
      :showSelectCol="false"
      :loading="tableInfo.loading"
      :columns="tableInfo.columns"
      :dataSource="tableInfo.list"
      :pagination="pagination"
      :tableHeight="460"
      :actionRender="renderTableBtnAction"
      @pageChange="handlePageChange"
      @pageSizeChange="handlePageSizeChange"
    >
      <el-row type="flex" slot="content_context" justify="space-between">
        <el-button
          v-if="showBtn('导出') && supplierExportConfig.supplier"
          size="mini"
          type="primary"
          icon="el-icon-download"
          :loading="exportLoading"
          @click="handleExport"
          >导出</el-button
        >
        <el-checkbox-group v-model="timeRange.value" @change="handleSelectTimeRange">
          <el-checkbox
            v-for="time in timeRange.list"
            :key="time.value"
            :label="time.value"
          >{{ time.label }}</el-checkbox>
        </el-checkbox-group>
      </el-row>
    </basic-table>
  </el-card>
</div>
</template>
<script>
import { getBtnsId } from '@/libs/btnsPermission';
import BasicPage from '@/mixins/supplier/basicPage';
import Dict from '@/mixins/supplier/dict';
import BasicForm from '@/components/supplier/BasicForm';
import BasicTable from '@/components/supplier/BasicTable';
import { FORM_ITEM_LIST, TABLE_COLUMNS } from './constants';
import { getTableAction } from '@/pages/supplier/utils/btnsUtils';
import { isResponseSuccess } from '@/pages/supplier/utils/bizUtils';
import {
  queryNearQualificationExpirationDateListService,
  exportQualificationExpirationListService
} from '@/api/supplier/management/nearQualificationExpirationDate';
import { createExcelByExport } from '@/utils/bizUtils';

export default {
  mixins: [BasicPage, Dict],
  components: {
    BasicForm,
    BasicTable
  },
  data () {
    return {
      timeRange: {
        value: [],
        list: [
          { label: '近7天内到期', value: 7 },
          { label: '近14天内到期', value: 14 },
          { label: '近30天内到期', value: 30 },
          { label: '近60天内到期', value: 60 },
          { label: '已过期', value: -1 },
        ]
      },
      formItemList: FORM_ITEM_LIST,
      formData: {
        supplierCode: '', // 供应商编码
        supplierName: '', // 供应商名称
        qualification: '', // 资质名称
        updateTime: [], // 变更时间
        managementAreaId: '', // 管理区域
        belongDepartment: '', // 归属中心
        cooperativeBrandId: '', // 合作品牌
      },
      tableInfo: {
        list: [],
        columns: TABLE_COLUMNS,
        loading: false,
        selection: []
      },
    }
  },
  computed: {
    // 表单入参
    formParams () {
      const [startTime = '', endTime = ''] = this.formData['updateTime'];
      let params = {
        ...this.formData,
        startTime,
        endTime,
      };
      delete params.updateTime;
      return params;
    }
  },
  mounted () {
    this.handleQueryForm();
  },
  methods: {
    renderTableBtnAction (h, { row }) {
      let actionList = [{ label: '维护资质', method: this.handleMaintainQualification, hasAuth: true }];
      if (!row.supplierClassify) { actionList = []; } // 边界处理 - 如果没有供应商类别，就不展示按钮
      return getTableAction({ h, row, actionList, showBtn: this.showBtn });
    },
    // 维护资质
    handleMaintainQualification (row) {
      this.skipToQualificationEditPage(row.supplierClassify, row.supplierId);
    },
    // 选择时间筛选范围
    handleSelectTimeRange (val) {
      // checkbox 单选
      if (val.length > 1) { this.timeRange.value = val.splice(1, 1); }
      const hasVal = this.timeRange.value.length > 0;
      if (hasVal) { this.formData.updateTime = []; } // 如果有选中时间范围，就清空表单的更新时间
      this.getTableData();
    },
    // 跳转资质编辑页
    skipToQualificationEditPage (type, id) {
      const pathByType = {
        40332: 'editQualifiedSupplier', // 合格供应商
        40331: 'editPotentialSupplier', // 潜在供应商
      }
      this.$router.push({
        name: pathByType[type] || '',
        query: { id, tab: 5, isReadonlyOtherTabs: 1, disableOtherTabs: 1 }
      });
    },
    // 获取表单数据
    getFormData (formData) {
      this.formData = formData;
      // 表单筛选条件有时间内容，清空单选checkbox内容
      const hasTime = formData.updateTime.length > 0;
      if (hasTime) { this.timeRange.value = []; }
    },
    // 获取表单查询入参
    getParamsBySearchForm () {
      const { current, size } = this.pagination;
      return { ...this.formParams, current, size, recentDay: this.timeRange.value[0] };
    },
    // 获取表格数据
    async getTableData () {
      sessionStorage.setItem('buttonId', getBtnsId('查询'));
      this.tableInfo.loading = true;
      const res = await queryNearQualificationExpirationDateListService(this.getParamsBySearchForm());
      this.tableInfo.loading = false;
      if (isResponseSuccess(res)) {
        this.tableInfo.list = res.result?.records || [];
        this.pagination.total = res.result.total;
      }
    },
    // 导出
    handleExport () {
      this.exportLoading = true;
      exportQualificationExpirationListService(this.getParamsBySearchForm()).then(res => {
        this.exportLoading = false;
        createExcelByExport({ excelTitle: '临期资质管理', res })
      })
    }
  }
}
</script>
